// cloudfunctions/manageorders/index.js
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

// --- *** 新增：管理员 OPENID *** ---
const ADMIN_OPENID = '41b03074e1bb154e164f0a56873bf6d0';

/**
 * 入口函数
 * @param {object} event - 包含 action (操作类型), orderId (订单ID), status (新状态)
 */
exports.main = async (event, context) => {
  const { action, orderId, status } = event;

  // --- *** 新增：权限校验 *** ---
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;

  if (openid !== ADMIN_OPENID) {
    return {
      success: false,
      message: '无权操作'
    };
  }
  // --- *** 权限校验结束 *** ---

  try {
    switch (action) {
      // 获取所有订单列表
      case 'getList':
        const res = await db.collection('orders').orderBy('createTime', 'desc').get();
        // (可选) 可以在云函数端就格式化时间
        // res.data.forEach(order => {
        //   order.createTimeFormatted = new Date(order.createTime).toLocaleString();
        // });
        return {
            success: true,
            data: res.data
        };
      
      // 更新订单状态
      case 'updateStatus':
        if (!orderId || !status) {
          return { success: false, message: '缺少必要参数' };
        }
        await db.collection('orders').doc(orderId).update({
          data: { 
            printStatus: status 
          },
        });
        return { success: true };
        
      // (未来可扩展：删除订单)
      // case 'deleteOrder':
      //   if (!orderId) {
      //     return { success: false, message: '缺少 orderId' };
      //   }
      //   await db.collection('orders').doc(orderId).remove();
      //   return { success: true };

      default:
        return {
          success: false,
          message: '未知的操作类型'
        }
    }
  } catch (e) {
    console.error('操作订单失败', e);
    return {
      success: false,
      error: e
    }
  }
};